package com.young.lib_fragments.utils

import android.util.Log
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.young.lib_fragments.bean.FmBackStackEntry

/**
 * @author huangzehui
 * @date 2025/1/21 13:04 周二
 * @description 处理一些异常的回退栈（例如Fragment被remove，但是回退栈还在，这个时候，你虽然看的了被remove的Fragment的上个Fragment，但是按返回，好像没有什么反应，其实是有个隐藏的回退栈）
 */
object HandleExceptionBackStackUtil {

    // Fragment 的回退栈 集合
    private var mFmBackStackEntryMap = mutableMapOf<Any, MutableList<FmBackStackEntry>>()

    // 回退栈的个数（用来做回退栈的时候使用）
    private var mFmBackStackCountMap = mutableMapOf<Any, Int>()


    /**
     * 处理一些异常的回退栈（例如Fragment被remove，但是回退栈还在，这个时候，你虽然看的了被remove的Fragment的上个Fragment，但是按返回，好像没有什么反应，其实是有个隐藏的回退栈）
     */
    @JvmStatic
    fun handleExceptionBackStack(fragmentManager: FragmentManager?) {

        if (fragmentManager != null) {
            val lastCount = mFmBackStackCountMap[fragmentManager] ?: 0

            val backStackEntryCount = fragmentManager.backStackEntryCount


            mFmBackStackCountMap[fragmentManager] = backStackEntryCount

            if (lastCount < backStackEntryCount) {
                return
            }


            if (backStackEntryCount > 0) {

                val fmBackStackEntries = mFmBackStackEntryMap[fragmentManager]

                Log.e(
                    "young_test9090909",
                    "handleExceptionBackStack: fmBackStackEntries = ${fmBackStackEntries} ${fragmentManager}"
                )
                if (fmBackStackEntries.isNullOrEmpty()) {
                    return
                }

                // 需要移除的回退栈
                val deleteList = mutableListOf<FmBackStackEntry>()

                // 需要返回的次数
                var needBackCount = 0

                val tempFmBackStackEntries = fmBackStackEntries.reversed()

                var isFirst = true

                for (fmBackStackEntry in tempFmBackStackEntries!!) {

                    if (fmBackStackEntry.fm != null) {
//                        break
                        if (isFirst) {
                            isFirst = true
                            // 首次的不需要break，因为首次是栈顶，栈顶这时候还没有销毁
                        } else {
                            break
                        }
                        Log.e("dsdfdsf", "fr = ${fmBackStackEntry}")
                    }

                    // 是否需要从自定义Fragment返回栈集合中移除返回栈信息
                    var isNeedRemove = false

                    for (index in 0 until backStackEntryCount) {
                        val stackEntry = fragmentManager.getBackStackEntryAt(index)
                        Log.e("young_test9090909", "handleExceptionBackStack: ${stackEntry}")

                        val isIdEq = fmBackStackEntry.id == stackEntry.id
                        val isFmNull = fmBackStackEntry.fm == null

                        if (isIdEq) {
                            isNeedRemove = true
                        }
                        if (isFmNull) {
                            isNeedRemove = true
                        }

                        if (isFmNull && isIdEq) {
                            ++needBackCount
                        }
                    }

                    if (isNeedRemove) {
                        deleteList.add(fmBackStackEntry)
                    }

                }

                if (needBackCount > 0) {
                    repeat(needBackCount) {
                        fragmentManager.popBackStack()
                    }
                }

                if (deleteList.isNotEmpty()) {
                    fmBackStackEntries.removeAll(deleteList)
                }


            } else {
                clearAllBackTask()
            }
        }
    }


    // 回退栈相关 start

    /**
     * 将 fragment 绑定到回退栈中
     *
     * @param fragmentManager Fragment 管理器
     * @param fragment 需要绑定的 Fragment
     *
     */
    @JvmStatic
    fun bindFragmentToBackStackEntry(
        fragmentManager: FragmentManager?,
        fragment: Fragment
    ) {
        addFmBackStackEntry(
            fragmentManager, FmBackStackEntry(
                fm = fragment, id = 0
            )
        )
    }

    /**
     * 将 fragment 从回退栈中解绑
     *
     * @param fragmentManager Fragment 管理器
     * @param fragment 需要绑定的 Fragment
     *
     */
    fun unBindFragmentToBackStackEntry(
        fragmentManager: FragmentManager?,
        fragment: Fragment
    ) {
        // 顶部的自定义的fragment回退栈信息
        val topFmBackStackEntry = getTopBackStartEntryByFm(fragmentManager, fragment) ?: return
        topFmBackStackEntry.fm = null
    }


    /**
     * 绑定
     */
    @JvmStatic
    fun bindBackStackEntryId(fragmentManager: FragmentManager?, fragment: Fragment) {
        if (fragmentManager == null || mFmBackStackEntryMap.isEmpty()) {
            return
        }
        // 顶部的自定义的fragment回退栈信息
        val topFmBackStackEntry = getTopBackStartEntryByFm(fragmentManager, fragment) ?: return

        val backStackEntryCount = fragmentManager.backStackEntryCount

        // 系统的Fragment回退栈信息
        val backStackEntry = fragmentManager.getBackStackEntryAt(backStackEntryCount - 1)
        topFmBackStackEntry.id = backStackEntry.id
    }

    /**
     * 通过 Fragment 获取栈顶的回推栈信息
     *
     * @param fragmentManager Fragment 管理器
     * @param fragment Fragment
     *
     * @return 栈顶的回退栈信息
     */
    @JvmStatic
    fun getTopBackStartEntryByFm(
        fragmentManager: FragmentManager?,
        fragment: Fragment
    ): FmBackStackEntry? {
        val fmBackStackEntryList = getFmBackStackEntryList(fragmentManager)
        if (fmBackStackEntryList.isNullOrEmpty()) {
            return null
        }
        return fmBackStackEntryList.reversed().find { it.fm == fragment }
    }

    /**
     * 获取栈顶的回推栈信息
     *
     * @param fragmentManager Fragment 管理器
     *
     * @return 栈顶的回退栈信息
     */
    @JvmStatic
    fun getTopBackStackEntry(fragmentManager: FragmentManager?): FmBackStackEntry? {
        val fmBackStackEntryList = getFmBackStackEntryList(fragmentManager)
        if (fmBackStackEntryList.isNullOrEmpty()) {
            return null
        }
        return fmBackStackEntryList.last()
    }

    /**
     * 添加回退栈
     *
     * @param fragmentManager Fragment 管理器
     * @param entry 回退栈实体
     *
     */
    @JvmStatic
    fun addFmBackStackEntry(fragmentManager: FragmentManager?, entry: FmBackStackEntry) {
        if (fragmentManager == null) {
            return
        }
        var fmBackStackEntryList = getFmBackStackEntryList(fragmentManager)
        if (fmBackStackEntryList == null) {
            fmBackStackEntryList = mutableListOf()
            mFmBackStackEntryMap[fragmentManager] = fmBackStackEntryList
        }
        if (!fmBackStackEntryList.contains(entry)) {
            fmBackStackEntryList.add(entry)
        }
    }

    /**
     * 获取 Fragment 回退栈集合
     *
     * @param fragmentManager Fragment 管理器
     *
     * @return  Fragment 回退栈集合
     */
    private fun getFmBackStackEntryList(fragmentManager: FragmentManager?): MutableList<FmBackStackEntry>? {
        if (fragmentManager == null) {
            return null
        }
        val fmBackStackEntries = mFmBackStackEntryMap[fragmentManager]
        if (fmBackStackEntries.isNullOrEmpty()) {
            return null
        }
        return fmBackStackEntries
    }

    /**
     * 清空所有的自定义回退栈顶
     */
    @JvmStatic
    fun clearAllBackTask() {
        if (mFmBackStackEntryMap.isEmpty()) {
            return
        }

        for (entry in mFmBackStackEntryMap) {
            val list = entry.value
            if (list.isEmpty()) {
                continue
            }
            for (stackEntry in list) {
                stackEntry.fm = null
            }
        }

        mFmBackStackEntryMap.clear()
    }


    // 回退栈相关 end

}